import request from "@/utils/request";

function buildMap(list, key, contentKey) {
  const map = {};
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    map[item[key]] = contentKey ? item[contentKey] : item;
  }
  return map;
}

const state = {
  companyId: localStorage.getItem("hr_companyId"),
  companyName: localStorage.getItem("hr_companyName"),
  companyList: [],
  companyMap: {},
  isCompany: null,
  color: "",
  adminNavState: null,
  channelsList: [] // 渠道
};

const mutations = {
  CHANNELS_LIST: (state, channelsList) => {
    state.channelsList = channelsList;
  },
  updateCompany: (state, payload) => {
    state.companyId = payload.companyId || payload.id;
    if (!payload.companyName && !payload.name) {
      const entry = state.companyList.filter((item) => item.id === state.companyId);
      if (entry && entry.length > 0) {
        state.companyName = entry[0].name;
      }
    } else {
      state.companyName = payload.companyName || payload.name;
    }
    localStorage.setItem("hr_companyId", state.companyId);
    localStorage.setItem("hr_companyName", state.companyName);
  },
  clearCompany: (state) => {
    state.companyId = null;
    state.companyName = null;
  },
  updateCompanyList(state, data) {
    if (data && data.length > 0) {
      state.companyList = data;
      state.companyMap = buildMap(data, "id");
      const theIdx = data.findIndex((item) => item.id === state.companyId);
      // 如果当前保存的用工单位信息不在列表，写入列表中的第一项为当前用工单位；如果存在，则不变
      // 处理的场景包括用工单位增删改查、切换租户等
      if (theIdx === -1) {
        state.companyId = data[0]["id"];
        state.companyName = data[0]["name"];
        localStorage.setItem("hr_companyId", state.companyId);
        localStorage.setItem("hr_companyName", state.companyName);
      }
    } else {
      state.companyList = [];
      state.companyMap = [];
      state.companyId = null;
      state.companyName = null;
      localStorage.setItem("hr_companyId", state.companyId);
      localStorage.setItem("hr_companyName", state.companyName);
    }
  },
  setIsCompany(state, payload) {
    state.isCompany = payload;
  },
  color(state, payload) {
    state.color = payload.color;
  },
  setAdminNavState: (state, payload) => {
    state.adminNavState = payload;
  },
  clearAdminNavState: (state) => {
    state.adminNavState = "workbench";
  },
  reload(state) {
    localStorage.setItem("hr_companyId", state.companyId);
    localStorage.setItem("hr_companyName", state.companyName);
  }
};

const actions = {
  loadCompanyList: ({ commit }) => {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve, reject) => {
      const clRes = await request({
        url: "/hr/api/v1/companies/listAll",
        routeChangeCancel: false
      }).catch((err) => {
        reject(err);
      });
      if (clRes && clRes.code === 200) {
        commit("updateCompanyList", clRes.data);
        resolve(true);
      } else {
        reject(false);
      }
    });
  },
  loadChannelsList: async ({ commit }) => {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve, reject) => {
      const channelRes = await request("/hr/api/v1/channels/listAll").catch((err) => {
        console.log("updateChannelList error", err);
        reject(err);
      });
      if (channelRes && channelRes.code === 200) {
        commit("CHANNELS_LIST", channelRes.data);
        resolve(true);
      } else {
        reject(false);
      }
    });
  },
  getIsCompany: ({ commit, state }) => {
    request({ url: `/hr/api/v1/users/userIsSuperme` }).then(({ data }) => {
      commit("setIsCompany", data);
    });
  },
  findCompanyItem({ state }, companyId) {
    const list = state.companyList;
    if (list && list.length > 0) {
      const item = list.find((li) => li.id === companyId);
      if (item) {
        return item;
      }
    }
    return false;
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
